package stack_queue.queue.impl;

import stack_queue.queue.Queue;

import java.util.NoSuchElementException;

public class CycleSeqQueue implements Queue {
    private final int[] elementData;
    private int size;
    private int frontIndex;
    private int rearIndex;
    public CycleSeqQueue(int k){
        elementData = new int[k];
        size = 0;
    }
    public int getSize(){
        return size;
    }
    //入队操作
    @Override
    public void offer(int value) {
        if (size == elementData.length){
            throw new NoSuchElementException("队列已满！");
        }
        elementData[rearIndex] = value;
        size++;
        rearIndex++;
        if (rearIndex == elementData.length){
            rearIndex = 0;
        }
    }

    @Override
    public int poll() {
        if (size == 0){
            throw new NoSuchElementException("队列为空！");
        }
        int oldValue = elementData[frontIndex];
        size--;
        frontIndex++;
        if (rearIndex == elementData.length){
            rearIndex = 0;
        }
        return oldValue;
    }

    @Override
    public int peek() {
        if (size == 0){
            throw new NoSuchElementException("队列为空！");
        }
        return elementData[frontIndex];
    }
    public int rear(){
        if (size == 0){
            throw new NoSuchElementException("队列为空！");
        }
        int index = rearIndex - 1;
        if(index == -1){
            index = elementData.length-1;
        }
        return elementData[index];
    }
}
